package com.fusheng.springcloud.controller;


import com.fusheng.springcloud.pojo.Dept;
import com.fusheng.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept){
        return deptService.addDept(dept);
    }

    /**
     *
     * 通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
     * @RequestMapping(value=”user/{id}/{name}”)
     * 请求路径：http://localhost:8080/hello/test/1/maomao
     * @param id
     * @return
     */
    @GetMapping("/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){

        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("获取失败！！");
        }
        return dept;
    }

    @GetMapping("/dept/list")
    @HystrixCommand //在监控页面进行监视
    public List<Dept> queryAll(){
        return deptService.queryAll();
    }

    //注册进来的微服务 获取一些消息
    @GetMapping("/dept/discovery")
    public Object discovery(){
        //获取微服务列表清单
        List<String> services = discoveryClient.getServices();
        System.out.println("discovery => "+services);

        //得到一个具体的微服务信息，通过具体的微服务id applicationName
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");

//        instances.forEach(System.out::println);
        for (ServiceInstance instance :instances) {
            System.out.println(
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri()+"\t"+
                    instance.getServiceId()
            );
        }
        return this.discoveryClient;
    }
}
